#include "wireitem.h"
#include <QPainterPath>
#include <QPen>

Wire::Wire(const QPointF &start, const QPointF &end, QGraphicsItem *parent)
    : QGraphicsPathItem(parent)
{
    setPen(QPen(Qt::red, 4));
    createPath(start, end);
}

void Wire::setColor(const QColor &color)
{
    setPen(QPen(color, 4));
}

void Wire::createPath(const QPointF &start, const QPointF &end)
{
    QPainterPath path;
    path.moveTo(start);

    const qreal deltaX = end.x() - start.x();
    const qreal deltaY = end.y() - start.y();

    // 智能路径规划算法
    if(qAbs(deltaX) > qAbs(deltaY)){
        // 水平优先
        path.lineTo(start.x() + deltaX/2, start.y());
        path.lineTo(start.x() + deltaX/2, end.y());
    } else {
        // 垂直优先
        path.lineTo(start.x(), start.y() + deltaY/2);
        path.lineTo(end.x(), start.y() + deltaY/2);
    }
    path.lineTo(end);

    // 避免重叠修正
    if(qFuzzyCompare(path.length(), 0)) {
        path = QPainterPath();
        path.addEllipse(start, 2, 2);
    }

    setPath(path);
}
